package com.example.dw.controller;

import com.example.dw.common.Result;
import com.example.dw.dto.*;
import com.example.dw.entity.*;
import com.example.dw.service.CourseService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 课程控制器
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/course")
@Tag(name = "课程管理", description = "课程相关的API接口")
public class CourseController {

    @Autowired
    private CourseService courseService;

    /**
     * 根据ID获取课程详情
     */
    @GetMapping("/courseL/{courseid}")
    @Operation(summary = "根据ID获取课程详情", description = "根据课程ID获取课程的详细信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "课程详情获取成功"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "404", description = "课程不存在")
    })
    public Result<Course> getCourseById(HttpServletRequest request, @PathVariable Integer courseid) {
        try {
            Integer userid = getCurrentUserId(request);
            Course course = courseService.getCourseById(courseid);
            return Result.success(course);
        } catch (Exception e) {
            log.error("根据ID获取课程详情失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加课程评论
     */
    @PostMapping("/addComment")
    @Operation(summary = "添加课程评论", description = "添加课程评论到指定课程")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "评论添加成功"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "404", description = "课程不存在")
    })
    public Result<Void> addCourseComment(HttpServletRequest request,
                                         @Validated @RequestBody CourseCommentDTO commentDTO) {
        try {
            Integer userid = getCurrentUserId(request);
            courseService.addCourseComment(userid, commentDTO);
            return Result.success("评论成功");
        } catch (Exception e) {
            log.error("添加课程评论失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取课程评论
     */
    @GetMapping("/getComment/{courseid}")
    @Operation(summary = "获取课程评论", description = "获取指定课程的所有评论")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "评论获取成功"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "404", description = "课程不存在")
    })
    public Result<List<CourseComment>> getCourseComment(HttpServletRequest request, @PathVariable Integer courseid) {
        try {
            Integer userid = getCurrentUserId(request);
            List<CourseComment> comments = courseService.getCourseComment(courseid);
            return Result.success(comments);
        } catch (Exception e) {
            log.error("获取课程评论失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页获取课程评论
     */
    @PostMapping("/getCommentByPage")
    @Operation(summary = "分页获取课程评论", description = "根据条件分页获取课程评论")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "评论分页获取成功"),
            @ApiResponse(responseCode = "401", description = "未授权访问")
    })
    public Result<Map<String, Object>> getCourseCommentByPage(HttpServletRequest request,
                                                               @Validated @RequestBody CourseCommentDTO commentDTO) {
        try {
            Integer userid = getCurrentUserId(request);
            Map<String, Object> result = courseService.getCourseCommentByPage(commentDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("分页获取课程评论失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 收藏/取消收藏课程
     */
    @PostMapping("/changeFavorite")
    @Operation(summary = "收藏/取消收藏课程", description = "切换指定课程的收藏状态")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "收藏状态切换成功"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "404", description = "课程不存在")
    })
    public Result<Void> changeFavorite(HttpServletRequest request,
                                       @Validated @RequestBody CourseFavoriteDTO favoriteDTO) {
        try {
            Integer userid = getCurrentUserId(request);
            favoriteDTO.setUserid(userid);
            courseService.changeFavorite(userid, favoriteDTO);
            return Result.success("操作成功");
        } catch (Exception e) {
            log.error("切换收藏状态失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 检查用户是否收藏了课程
     */
    @PostMapping("/isFavorite")
    @Operation(summary = "检查用户是否收藏了课程", description = "检查当前用户是否收藏了指定课程")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "收藏状态检查成功"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "404", description = "课程不存在")
    })
    public Result<Boolean> isFavorite(HttpServletRequest request,
                                      @RequestBody CourseFavoriteDTO favoriteDTO) {
        try {
            Integer userid = getCurrentUserId(request);
            Boolean isFavorite = courseService.isFavorite(userid, favoriteDTO.getCourseid());
            return Result.success(isFavorite);
        } catch (Exception e) {
            log.error("检查收藏状态失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据类型分页获取课程
     */
    @PostMapping("/getCourseByType")
    @Operation(summary = "根据类型分页获取课程", description = "根据课程类型和条件分页获取课程")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "课程分页获取成功"),
            @ApiResponse(responseCode = "401", description = "未授权访问")
    })
    public Result<Map<String, Object>> getCourseByType(@RequestBody CourseQueryDTO queryDTO) {
        try {
            Map<String, Object> result = courseService.getCourseByType(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("根据类型分页获取课程失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取所有课程类型
     */
    @GetMapping("/getAllType")
    @Operation(summary = "获取所有课程类型", description = "获取所有可用的课程类型")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "课程类型获取成功")
    })
    public Result<List<CourseType>> getCourseTypes() {
        try {
            List<CourseType> courseTypes = courseService.getCourseTypes();
            return Result.success(courseTypes);
        } catch (Exception e) {
            log.error("获取所有课程类型失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页获取课程类型（Web端素质测评）
     */
    @PostMapping("/getAllType")
    @Operation(summary = "分页获取课程类型（Web端素质测评）", description = "根据条件分页获取Web端素质测评课程类型")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "课程类型分页获取成功"),
            @ApiResponse(responseCode = "401", description = "未授权访问")
    })
    public Result<Map<String, Object>> getCourseTypeByPage(@RequestBody CourseQueryDTO queryDTO) {
        try {
            Map<String, Object> result = courseService.getCourseTypeByPage(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("分页获取课程类型失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 模糊搜索课程
     */
    @PostMapping("/getCourseMOHu")
    @Operation(summary = "模糊搜索课程", description = "根据关键词模糊搜索课程")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "课程模糊搜索成功"),
            @ApiResponse(responseCode = "401", description = "未授权访问")
    })
    public Result<Map<String, Object>> getCourseMOHu(@RequestBody CourseQueryDTO queryDTO) {
        try {
            Map<String, Object> result = courseService.getCourseMOHu(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("模糊搜索课程失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新用户学习状态
     */
    @PostMapping("/updatePeriodState")
    @Operation(summary = "更新用户学习状态", description = "更新当前用户对指定课程的学习状态")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "学习状态更新成功"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "404", description = "课程不存在")
    })
    public Result<Void> updatePeriodState(HttpServletRequest request,
                                          @Validated @RequestBody StudyPeriodDTO studyPeriodDTO) {
        try {
            Integer userid = getCurrentUserId(request);
            studyPeriodDTO.setUserid(userid);
            courseService.updatePeriodState(userid, studyPeriodDTO);
            return Result.success("更新学习状态成功");
        } catch (Exception e) {
            log.error("更新用户学习状态失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据类型分页获取课程（Web端）
     */
    @PostMapping("/getCourseByTypePage")
    @Operation(summary = "根据类型分页获取课程（Web端）", description = "根据课程类型和条件分页获取Web端课程")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "课程分页获取成功"),
            @ApiResponse(responseCode = "401", description = "未授权访问")
    })
    public Result<Map<String, Object>> getCourseByTypePage(@RequestBody CourseQueryDTO queryDTO) {
        try {
            Map<String, Object> result = courseService.getCourseByTypePage(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("根据类型分页获取课程（Web端）失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 从请求中获取当前用户ID
     */
    private Integer getCurrentUserId(HttpServletRequest request) {
        Integer userid = (Integer) request.getAttribute("userid");
        if (userid == null) {
            throw new RuntimeException("未授权访问");
        }
        return userid;
    }
} 